package com.aegis.manage.service.sys.permission;

import cn.hutool.core.collection.CollectionUtil;
import com.aegis.manage.api.dto.RolePermissionDTO;
import com.aegis.manage.utils.AuthUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.aegis.common.mybatis.base.BaseServiceImpl;
import com.aegis.common.mybatis.model.PageResult;
import com.aegis.common.utils.AssertUtil;
import com.aegis.manage.api.request.AddPermissionRequest;
import com.aegis.manage.mapper.SysMenuPermissionMapper;
import com.aegis.manage.mapper.SysPermissionMapper;
import com.aegis.manage.mapper.SysRoleMenuPermissionMapper;
import com.aegis.manage.mapper.SysRolePermissionMapper;
import com.aegis.manage.model.dos.SysMenuPermission;
import com.aegis.manage.model.dos.SysPermission;
import com.aegis.manage.model.dos.SysRoleMenu;
import com.aegis.manage.model.dos.SysRolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * (SysPermission)表服务实现类
 *
 * @author makejava
 * @since 2024-02-12 20:03:31
 */
@Service("sysPermissionService")
public class SysPermissionServiceImpl extends BaseServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;

    @Autowired
    private SysMenuPermissionMapper sysMenuPermissionMapper;

    @Autowired
    private SysRoleMenuPermissionMapper sysRoleMenuPermissionMapper;


    @Override
    public List<SysPermission> selectUserPermissionByUserId(String userId) {
        boolean admin = AuthUtil.isAdmin(userId);
        if (admin) {
            return selectAll();
        }
        return baseMapper.selectPermissionByUserId(userId);
    }

    @Override
    public List<SysPermission> selectAll() {
        return baseMapper.selectList(new QueryWrapper<>());
    }


    @Override
    public void addPermission(AddPermissionRequest addPermissionRequest) {
        AssertUtil.operateFailed(selectCount(SysPermission::getPermission, addPermissionRequest.getPermission()) > 0, "已存在相同的权限key");
        AssertUtil.operateFailed(selectCount(SysPermission::getApi, addPermissionRequest.getApi()) > 0, "已存在相同的api权限");
        SysPermission sysPermission = new SysPermission();
        sysPermission.setPermission(addPermissionRequest.getPermission());
        sysPermission.setApi(addPermissionRequest.getApi());
        sysPermission.setName(addPermissionRequest.getPermissionName());
        AssertUtil.operateFailed(baseMapper.insert(sysPermission) <= 0);
    }

    @Override
    public PageResult<SysPermission> selectPermissionPage(int current, int size) {
        return selectPage(current, size, null);
    }

    @Override
    public void delPermission(List<String> id) {
        baseMapper.deleteBatchIds(id);
    }

    @Override
    public void bindRolePermission(String roleId, Set<String> permissionIds) {
        //角色已有的权限
        List<SysRolePermission> sysRolePermissions =
                sysRolePermissionMapper.selectList(new LambdaQueryWrapper<SysRolePermission>()
                        .eq(SysRolePermission::getRoleId, roleId));
        //需要绑定的权限id
        List<String> bindPermissionId = new ArrayList<>(permissionIds);
        if (CollectionUtil.isNotEmpty(sysRolePermissions)) {
            List<String> hasPermission = sysRolePermissions.stream()
                    .map(sysRolePermission -> sysRolePermission.getPermissionId())
                    .collect(Collectors.toList());
            bindPermissionId.retainAll(hasPermission);
        }
        AssertUtil.operateFailed(!sysRolePermissionMapper.saveBatch(bindPermissionId.stream().map(s -> {
            SysRolePermission sysRolePermission = new SysRolePermission();
            sysRolePermission.setPermissionId(s);
            sysRolePermission.setRoleId(roleId);
            return sysRolePermission;
        }).collect(Collectors.toList())), "添加失败");
    }

    @Override
    public void bindMenuPermission(String menuId, Set<String> permissionIds) {
        //菜单已绑定的权限
        List<SysMenuPermission> sysPermissionRoleDOS =
                sysMenuPermissionMapper.selectList(new LambdaQueryWrapper<SysMenuPermission>()
                        .eq(SysMenuPermission::getMenuId, menuId));
        //需要绑定的权限id
        List<String> bindPermissionId = new ArrayList<>(permissionIds);
        if (CollectionUtil.isNotEmpty(sysPermissionRoleDOS)) {
            List<String> hasPermission = sysPermissionRoleDOS.stream()
                    .map(sysPermissionRoleDO -> sysPermissionRoleDO.getPermissionId())
                    .collect(Collectors.toList());
            bindPermissionId.retainAll(hasPermission);
        }
        AssertUtil.operateFailed(!sysMenuPermissionMapper.saveBatch(bindPermissionId.stream().map(s -> {
            SysMenuPermission sysMenuPermission = new SysMenuPermission();
            sysMenuPermission.setPermissionId(s);
            sysMenuPermission.setMenuId(menuId);
            return sysMenuPermission;
        }).collect(Collectors.toList())), "添加失败");
    }

    @Override
    public void bindRoleMenu(String roleId, Set<String> menuIds) {
        //角色已有的权限
        List<SysRolePermission> sysRolePermissions =
                sysRolePermissionMapper.selectList(new LambdaQueryWrapper<SysRolePermission>()
                        .eq(SysRolePermission::getRoleId, roleId));
        //需要绑定的菜单id
        List<String> bindMenuId = new ArrayList<>(menuIds);
        if (CollectionUtil.isNotEmpty(sysRolePermissions)) {
            List<String> hasPermission = sysRolePermissions.stream()
                    .map(sysRolePermission -> sysRolePermission.getPermissionId())
                    .collect(Collectors.toList());
            bindMenuId.retainAll(hasPermission);
        }
        AssertUtil.operateFailed(!sysRoleMenuPermissionMapper.saveBatch(bindMenuId.stream().map(s -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(s);
            sysRoleMenu.setRoleId(roleId);
            return sysRoleMenu;
        }).collect(Collectors.toList())), "添加失败");
    }

    @Override
    public List<RolePermissionDTO> selectRolePermissionByRoleId(String roleId) {
        return getBaseMapper().selectRolePermissionByRoleId(roleId);
    }

}

